require 'iconv'

class AddressesController < ApplicationController
  before_filter :login_required, :authorization_required, :find_customer
  
  
  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :create ], :redirect_to => { :action => :index }
  verify :method => :put, :only => [ :update ], :redirect_to => { :action => :index }
  verify :method => :delete, :only => [ :destroy, :destroy_selected ], :redirect_to => { :action => :index }

  def index
    respond_to do |format|
      format.html {render :action => 'list.rhtml'}
      format.js {render :action => 'list.rjs'}
      format.xml {render :xml => @customer.addresses.to_xml}
    end
  end
  
  def show
    @address = Address.find(params[:id])
  end
  
  def new
    @address = Address.new
    respond_to do |format|
      format.html {render :action => 'new.rhtml'}
      format.js {render :action => 'new.rjs'}
    end
  end
  
  def create
    address = Address.new(params[:address])
    @customer.addresses << address
    if @customer.save
      redirect_to :controller => 'customers', :action => 'show', :id => @customer unless request.xhr?
    else
      render :action => 'new' unless request.xhr?
    end
  end
  
  def edit
    @address = Address.find(params[:id])
    @customer = @address.customer
    respond_to do |format|
      format.html {render :action => 'edit.rhtml'}
      format.js {render :action => 'edit.rjs'}
    end
  end
  
  def update
    @address = Address.find(params[:id])
    if @address.update_attributes(params[:address])
      redirect_to :controller => 'customers', :action => 'show', :id => @customer unless request.xhr?
    else
      render :action => 'edit' unless request.xhr?
    end
  end
  
  def destroy
    Address.find(params[:id]).destroy
    list
  end
  
  def print
    @address = Address.find(params[:id])
    street = @address.street1
    street = @address.street2 unless @address.street2.empty?
    ic = Iconv.new("LATIN2", "UTF-8")
    address_text = ic.iconv("#{@customer.name}\r#{street}\r#{@address.postal} #{@address.city.upcase}")
    system "print_address.sh \"#{address_text}\""
    redirect_to :controller => 'customers', :action => 'show', :id => @customer unless request.xhr?
  end
  
  def destroy_selected
    unless params[:selected].nil?
      params[:selected].each do |id|
        address = Address.find(id)
        @customer = address.customer
        address.destroy
      end
    end
    redirect_to :controller => 'customers', :action => 'show', :id => @customer unless request.xhr?
  end
end
